<template>
  <!-- 生产日报表 -->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline" :rules="formRules" ref="searchForm">
        <el-form-item label="状态" style="width: 180px">
          <el-select v-model="searchParam.property" placeholder="请选择状态" @change="propertyChange">
            <el-option v-for="item in propertyList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="产品" style="width: 250px" prop="materalId">
          <el-select v-model="searchParam.materalId" remote
                     :remote-method="remoteMethod" filterable placeholder="请选择产品"
                     @change="handleTeamChange">
            <el-option v-for="(item, index) of materialList" :key="index" :label="item.productName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="工序" style="width: 380px" prop="procedureNames">
          <el-select v-model="searchParam.procedureNames" clearable collapse-tags
                     collapse-tags-tooltip
                     :max-collapse-tags="2" placeholder="请选择工序" multiple filterable>
            <el-option v-for="item in uniqueProcedureNames" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间" prop="times" style="width: 450px">
          <el-date-picker v-model="searchParam.times" type="datetimerange" start-placeholder="开始时间"
                          end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
          <!-- <el-date-picker v-model="searchParam.times" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD" /> -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="submitForm()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" :span-method="arraySpanMethod" border
                height="calc(100vh - 290px)">
        <el-table-column label="序号" align="center" width="70" fixed>
          <template #default="scope"> {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="materialNo" label="物料" align="center" min-width="200" fixed/>
        <el-table-column prop="procedureName" label="工序名称" align="center" min-width="200" fixed/>
        <el-table-column prop="curren" label="时间" align="center" min-width="200" fixed>
          <template #default="scope"> {{ scope.row.curren.slice(0, -9) }}</template>
        </el-table-column>
        <el-table-column prop="daySendWorkNumber" label="计划产量" align="center" min-width="200"/>
        <el-table-column prop="dayCount" label="每日产量" align="center" min-width="200"/>
        <el-table-column prop="achievingRate" label="达成率" align="center" min-width="200"/>
        <el-table-column prop="qualifiedCount" label="合格数量" align="center" min-width="200"/>
        <el-table-column prop="percentOfPass" label="合格率" align="center" min-width="200"/>
        <el-table-column prop="accumulativeCount" label="累计产量" align="center" min-width="200"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {computed, reactive, ref, onMounted} from 'vue';
import {ElMessage, ElForm} from 'element-plus';
import {ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import axios from 'axios';
import moment from 'moment';

const searchForm = ref<InstanceType<typeof ElForm>>();

const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const pageTotal = ref(null); // 页面总数
const searchParam = ref({
  property: 0,
  times: [
    dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
});

const materialList = ref([]); // 物料表
const processData = ref([]); // 工序

const formRules = ref({
  materalId: [{required: true, message: '请选择物料', trigger: 'change'}],
  procedureNames: [{required: true, message: '请选择工序', trigger: 'change'}],
  times: [{required: true, message: '请选择时间', trigger: 'change'}]
});

const getSpanArr = (data) => {
  let spanArr = [];
  let spanArr1 = [];
  let pos = 0;
  let pos1 = 0;

  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.push(1);
      spanArr1.push(1);
      pos = 0;
      pos1 = 0;
    } else {
      // 检查物料名称是否相同
      if (data[i].materialNo === data[i - 1].materialNo) {
        spanArr[pos] += 1;
        spanArr.push(0);
        // 检查工序名称是否相同
        if (data[i].procedureName === data[i - 1].procedureName) {
          spanArr1[pos1] += 1;
          spanArr1.push(0);
        } else {
          spanArr1.push(1);
          pos1 = i;
        }
      } else {
        spanArr.push(1);
        spanArr1.push(1);
        pos = i;
        pos1 = i;
      }
    }
  }
  return [spanArr, spanArr1];
};

const arraySpanMethod = ({row, column, rowIndex, columnIndex}) => {
  // 获取合并信息数组
  const [spanArr, spanArr1] = getSpanArr(paginatedData.value);

  if (columnIndex === 1) { // 物料列
    const _row = spanArr[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col
    };
  } else if (columnIndex === 2) { // 工序名称列
    const _row = spanArr1[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col
    };
  }
};

const propertyChange = () => {
  if (searchParam.value.materalId) {
    searchParam.value.procedureNames = []
    handleTeamChange(searchParam.value.materalId)
  }
}

const propertyList = ref([{label: '正常', value: 0}, {label: '返工', value: 1}]);

const handleTeamChange = (value) => {
  searchParam.value.procedureIds = [];
  axiosInstance.get('/api/basedataProcedure/queryByMateralIdProcedure', {
    params: {materalId: value, property: searchParam.value.property}
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        processData.value = res.data;
        // searchParam.value.procedureIds = res.data.map(item => item.id);
        setList();
      });
};
const uniqueProcedureNames = ref([]);
const setList = () => {
  const list = JSON.parse(JSON.stringify(processData.value));
  const loop = list.reduce((unique, item) => {
    if (!unique.includes(item.procedureName)) {
      unique.push(item.procedureName);
    }
    return unique;
  }, []);
  uniqueProcedureNames.value = loop;
  searchParam.value.procedureNames = loop;
  console.log(loop, 'uniqueProcedureNamesuniqueProcedureNames');
};

const paginatedData = ref([]);
const workRoomList = ref([]); // 车间

const getOption = () => {
  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
  axiosInstance.post('/api/basedataProduct/getPage', {
    current: 1, pageSize: 50
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        materialList.value = res.data.records;
      });
};

const remoteMethod = (value) => {
  console.log(value);

  if (!value) {
    return;
  }
  axiosInstance.post('/api/basedataProduct/getPage', {
    current: 1, pageSize: 50, productName: value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        materialList.value = res.data.records;
      });
};

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/basedataProcedure/exportExcelProductionDay', {
    ...searchParam.value,
    ...{
      startDate: searchParam.value?.times?.[0],
      endDate: searchParam.value?.times?.[1]
    }
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '生产日报表' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


// 获取列表接口
const getList = () => {
  const ids = []; // 创建一个新数组来存放匹配的id

  // 假设 processData 是一个数组，每个元素都有一个 procedureName 和 id 属性
  processData.value.forEach(item => {
    // 检查当前元素的 procedureName 是否在 searchParam.procedureNames 中
    if (searchParam.value.procedureNames.includes(item.procedureName)) {
      ids.push(item.id); // 如果是，则将 id 添加到 ids 数组中
    }
  });

  searchParam.value.procedureIds = ids;


  // ids 现在包含了所有匹配的id
  axiosInstance.post('/api/basedataProcedure/productionDay', {
    ...searchParam.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = [];
        for (const item of res.data) {
          for (const itmes of item.children) {
            list.push({
              ...item,
              ...itmes
            });
          }
        }
        paginatedData.value = list;

        // const dateList = []
        // if (res.data && res.data.length > 0) {
        //   for (const item of res.data[0].children) {
        //     dateList.push(item.curren.slice(0,-9))
        //   }
        // }
        // console.log(dateList);

      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 提交表单
const submitForm = () => {
  searchForm.value?.validate((valid) => {
    if (valid) {
      getList();
    }
  });
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {
    property: 0,
    times: [
      dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  };
  pageSearch.value.current = 1;
  // getList();
};

onMounted(() => {
  // getList();
  getOption();
});
</script>
<style scoped></style>